package com.study.cloudAlibaba.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.study.cloudAlibaba.dao.OrderDao;
import com.study.cloudAlibaba.domain.Order;
import com.study.cloudAlibaba.service.AccountService;
import com.study.cloudAlibaba.service.OrderService;
import com.study.cloudAlibaba.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lzc
 * @date 2022/7/29 16:30
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    @Override
    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("------->下单开始");
        order.setStatus(0);
        //本应用创建订单
        orderDao.insert(order);

        //远程调用库存服务扣减库存
        log.info("------->order-service中扣减库存开始");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("------->order-service中扣减库存结束");

        //远程调用账户服务扣减余额
        log.info("------->order-service中扣减余额开始");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("------->order-service中扣减余额结束");

        //修改订单状态为已完成
        log.info("------->order-service中修改订单状态开始");
        //orderDao.update(order.getUserId(),0);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, order.getUserId())
                .eq(Order::getStatus,0);
        Order orderUpdate = orderDao.selectOne(wrapper);
        orderUpdate.setStatus(1);
        orderDao.updateById(orderUpdate);
        log.info("------->order-service中修改订单状态结束");

        log.info("------->下单结束");
    }

}
